package org.smarthings.test;

import org.smarthings.Callback;
import org.smarthings.Client;
import org.smarthings.Factory;
import org.smarthings.Message;
import org.smarthings.coap.CoapFactory;
import org.smarthings.http.HttpFactory;
import org.smarthings.mqtt.MqttFactory;

public class AbstractClient {
	protected static final Factory mqtt = new MqttFactory();
	protected static final Factory coap = new CoapFactory();
	protected static final Factory http = new HttpFactory();
	protected static String URI = "services/things/1/properties/1/value";
	protected static String TYPE = "application/json";

	public static void get(Factory factory) {
		System.out.println("--------- GET " + factory.getProtocol());
		Client client = factory.startNewClient();
		Message message = client.get(URI, TYPE);
		System.out.println("Getter -> " + message.toString());
		sleep(200);
		client.stop();
	}

	public static void post(Factory factory) {
		post(factory, factory.getClass().getName());
	}

	public static void post(Factory factory, String payload) {
		System.out.println("-------- POST " + factory.getProtocol() + " " + payload);
		Client client = factory.startNewClient();
		Message message = Message.createSimpleMessage(payload.getBytes(), factory.getProtocol(), URI, TYPE);
		client.post(message);
		sleep(200);
		client.stop();
	}

	public static void thread(final Factory factory) {
		new Thread() {
			public void run() {
				listen(factory, 60 * 60);
			};
		}.start();
		sleep(200);
	}

	public static void listen(Factory factory, int sleep) {
		System.out.println("------ LISTEN " + factory.getProtocol());
		Client client = factory.startNewClient();
		client.subscribe(URI, TYPE, new Callback() {
			public void message(Message message) {
				System.out.println("Callback -> " + message.toString());
			}
		});
		sleep(sleep * 1000);
		client.stop();
	}

	protected static void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}